package com.netcracker.ui.command;


import com.netcracker.entity.Right;
import com.netcracker.entity.record.PublisherRecord;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.PublisherService;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.WrongPublisherException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;


public class AddPublisherCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AddPublisherCommand.class);
    private final ServiceFacade serviceFacade;

    public AddPublisherCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
         Right right = (Right) request.getSession().getAttribute("right");
        if (right != null && right.equals(Right.ADMIN)) {
            PublisherService publisherService = serviceFacade.getPublisherService();
            String publisherName = request.getParameter("name");
            Integer countryID = Integer.parseInt(request.getParameter("country"));
            PublisherRecord publisherRecord = new PublisherRecord();
            publisherRecord.setCountryID(countryID);
            publisherRecord.setName(publisherName);
            try {
                publisherService.addPublisher(publisherRecord);
            } catch (DataTransmittingException ex) {
                request.setAttribute("error", "Ошибка обращения к БД.");
                LOGGER.error("DB error: ", ex);
                return "index.jsp";
            } catch (WrongPublisherException ex) {
                request.setAttribute("error", "Заполните все поля.");
                return "?action=newPublisher";
            }
            return "?action=allPublishers";
        } else {
            request.setAttribute("error", "Недостаточно прав на добавление издательства.");
            return "index.jsp";
        }
    } 
}
